import re
from rest_framework import serializers
from django_redis import get_redis_connection

# 数据入库选择ModelSerializer
from goods.models import SKU
from users.models import User, Address


class RegisterCreateUserSerializer(serializers.ModelSerializer):
    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6, allow_null=False, allow_blank=False,
                                     write_only=True)
    password2 = serializers.CharField(label='校验密码', allow_null=False, allow_blank=False, write_only=True)
    allow = serializers.CharField(label='是否同意协议', allow_null=False, allow_blank=False, write_only=True)
    token = serializers.CharField(label='登录状态token', read_only=True)  # 增加token字段

    class Meta:
        model = User
        fields = ['id', 'username', 'password', 'password2', 'mobile', 'sms_code', 'allow', 'token']

        extra_kwargs = {
            'id': {'read_only': True},
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    # 手机号校验
    def validate_mobie(self, value):
        if not re.match('1[3-9]\d{9}', value):
            raise serializers.ValidationError("手机号不满足规则")
        return value

    # 是否同意协议
    def validate_allow(self, value):
        if value == 'false':
            raise serializers.ValidationError('您未同意协议')

        return value

    # 密码短信
    def validate(self, attrs):
        # 密码
        password = attrs.get('password')
        password2 = attrs.get('password2')
        mobile = attrs.get('mobile')
        sms_code = attrs.get('sms_code')
        if password != password2:
            raise serializers.ValidationError('密码不一致')

        # 短信
        redis_conn = get_redis_connection('code')
        sms_code_radis = redis_conn.get('sms_%s' % mobile)
        if sms_code_radis is None:
            raise serializers.ValidationError('验证码已过期')

        if sms_code_radis.decode() != sms_code:
            raise serializers.ValidationError('验证码错误')

        return attrs

    def create(self, validated_data):

        # 删除多余字段
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        user = super().create(validated_data)

        # 修改密码
        user.set_password(validated_data['password'])
        user.save()

        from rest_framework_jwt.settings import api_settings
        # 补充生成记录登录状态的token
        # 获取jwt两个方法
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        # payload可以装载数据(用户数据)
        payload = jwt_payload_handler(user)
        # 进行编码
        token = jwt_encode_handler(payload)
        user.token = token

        return user


class UserCenterSerializer(serializers.ModelSerializer):
    """
      用户详细信息序列化器
      """

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


class UserEmaiSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('email',)


class AddressSerializer(serializers.ModelSerializer):

    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')


    def create(self, validated_data):
        #  我们并没有让前端传递用户的的 user_id 因为 我们是采用的jwt认证方式
        # 我们可以获取user_id 所以 validated_data 没有user_id
        # 但是我们在调用 系统的 crate方法的时候  Address.objects.create(**validated_data)
        # Address必须要 user_id 这个外键,所以就报错了
        # user = request.user
        #Address模型类中有user属性,将user对象添加到模型类的创建参数中
        validated_data['user'] = self.context['request'].user
        # return Address.objects.create(**validated_data)

        # super() 指向 单继承的 ModelSerializer
        return super().create(validated_data)

class UpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Address
        fields = ['title']


class UserHistorySerializer(serializers.ModelSerializer):
    """
        添加用户浏览记录序列化器
        """
    sku_id = serializers.IntegerField(label='商品编号', min_value=1, required=True)
    class Meta:
        model = SKU
        fields = ['sku_id']


class SKUSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKU
        fields = ('id', 'name', 'price', 'default_image_url', 'comments')
